﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Mvc.Ajax;
using System.Web.UI.WebControls;
using System.Web.Routing;
using System.Web.Script.Serialization;
using CoolCode.Linq.Expressions;

namespace CoolCode.Web.Mvc
{
	public static class DropDownTreeExtensions
	{
		public static MvcHtmlString DropDownTreeFor<T>(this HtmlHelper<T> htmlHelper, Expression<Func<T, object>> propertySpecifier, DropDownTreeSetting setting)
		{
			string propertyName = propertySpecifier.Body.GetMemberName();
			return DropDownTree(htmlHelper, propertyName, setting);
		}

		public static MvcHtmlString DropDownTree(this HtmlHelper htmlHelper, string name, DropDownTreeSetting setting)
		{
			return DropDownTree(htmlHelper, name, setting, null);
		}

		public static MvcHtmlString DropDownTree(this HtmlHelper htmlHelper, string name, DropDownTreeSetting setting, IDictionary<string, object> attributes)
		{
			//MvcHtmlString html = htmlHelper.DropDownList(name);
			var builder = new TagBuilder("select");
			builder.MergeAttributes(attributes);
			builder.MergeAttribute("name", name);
			string id = "d" + Guid.NewGuid().ToString("N");
			builder.MergeAttribute("id", id);

			string script = string.Format("$('{0}').dropdowntree({1});", JQueryHelper.FormatElement(id), setting);

			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(builder.ToString(TagRenderMode.Normal));
			stringBuilder.Append(htmlHelper.JavaScript(script));

			return MvcHtmlString.Create(stringBuilder.ToString());
		}
	}

	[Serializable]
	public class DropDownTreeSetting
	{
		public string url { get; set; }
		public int? width { get; set; }

		public override string ToString()
		{
			JavaScriptSerializer serializer = new JavaScriptSerializer();
			return serializer.Serialize(this);
		}
	}
}
